package com.tronsis.distribution.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tronsis.distribution.Constants;


/**
 * 微信支付回调Activity
 *
 * @author allen@tronsis.com
 */
public class WXPayEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    private static final String TAG = "WXPayEntryActivity";
    public static final String WX_PAY_RESULT_ACTION = "wx_pay_result_action";
    public static final String WX_PAY_ERR_CODE = "wechat_pay_err_code";
    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setFinishOnTouchOutside(true);

        api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID); // 微信开放平台appid
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {}

    /**
     * 支付结果回调
     *
     * @param resp
     */
    @Override
    public void onResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            Log.e(TAG, "errCode: " + resp.errCode + ", msg:" + resp.errStr );
            Intent intent = new Intent();
            intent.putExtra(WX_PAY_ERR_CODE, resp.errCode);
            intent.setAction(WX_PAY_RESULT_ACTION);
            sendBroadcast(intent); // 发送广播通知支付结果
            this.finish();
        }
    }
}